package com.example.service;

import com.example.server.SysClusterServer;
import com.example.utils.IPUtils;
import org.jgroups.Address;
import org.jgroups.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

@Service
public class SysClusterServiceImpl implements SysClusterService, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private SysClusterServer sysClusterServer;

    @Override
    public void destroy() throws Exception {
        this.sysClusterServer.stop();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.sysClusterServer = new SysClusterServer("s" + IPUtils.getServerId(), new SysClusterServer.SysClusterServerListener() {
            @Override
            public void receive(Message msg) {
                logger.warn("server收到消息: " + msg.getObject());
            }

            @Override
            public void up(Address address) {
                logger.warn("节点: " + address + " 上线 ...");
            }

            @Override
            public void down(Address address) {
                logger.warn("节点: " + address + " 下线 ...");
            }
        });
        this.sysClusterServer.start();
    }

    @Override
    public SysClusterServer getSysClusterServer() {
        return this.sysClusterServer;
    }
}
